package com.gouda.merchant.interceptor;

import com.themis.dto.BackendSystemUserDto;
import com.google.common.base.Strings;
import com.gouda.core.service.systemManage.MerchantUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: souu
 * Date: 15/5/4
 * Time: 下午1:40
 * To change this template use File | Settings | File Templates.
 */
@Slf4j
public class BackendLoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
//    private UserService userService;
    private MerchantUserService userService;

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
        String uid = this.getAdminUserId(request);
        if (Strings.isNullOrEmpty(uid)) {//未登录
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
            return false;
        }
//        BackendUserDto user = this.userService.getUserById(uid);
        BackendSystemUserDto user = userService.getUserById(uid);
        if (user == null) { //用户不存在
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
            return false;
        }
        return super.preHandle(request, response, handler);
    }

    private String getAdminUserId(HttpServletRequest req) {
        Cookie[] cookies = req.getCookies();
        String id = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("adminId".equals(cookie.getName())) {
                    if (StringUtils.isNotBlank(cookie.getValue())) {
                        id = cookie.getValue();
                    }
                }
            }
        }
        return id;
    }
}
